package com.namo.cchuser.service.impl;

import com.namo.cchcommon.api.ResultCode;
import com.namo.cchcommon.exception.ApiException;
import com.namo.cchuser.entity.User;
import com.namo.cchuser.mapper.UserMapper;
import com.namo.cchuser.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @author WangXin
 * @date 2021/4/19 10:25
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public User login(User user) {
        if (user == null){
            log.error("用户为空");
            throw new ApiException(ResultCode.FAILED);
        }
        //从请求中获取用户信息
        User user1 = userMapper.selectByOpenId(user.getOpenId());

        //判断openid和user是否为空，为空返回错误
        if (user1 == null){
            user.setId(UUID.randomUUID().toString());
            System.out.println(user);
            int insert = userMapper.insert(user);
        }else {
            user = user1;
            //更新用户信息
            userMapper.updateByPrimaryKeySelective(user1);
        }
        //根据openid查询用户
        //如果查到，则更新用户信息
        //如果没有查到就新建用户信息
        return user;
    }

    /**
     * 获取用户信息
     * @param id 用户ID
     * @return
     */
    @Override
    public User getUser(String id) {
        log.info("寻找用户信息，ID为：{}"+id);
        User user = userMapper.selectByPrimaryKey(id);
        //没有找到此用户
        if (user == null){
            log.warn("未寻找到用户信息，ID为：{}"+id);
            throw new ApiException(500L,"获取用户失败");
        }
        log.info("找到用户信息，ID为：{}"+id);
        return user;
    }
}
